from urllib import request,parse
import json

def fanyi(keyword):
    url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"

    #定义请求的参数，并编码转换
    data = {
        "i":keyword,
        'from':'AUTO',
        'to':'AUTO',
        'smartresult':'dict',
        'client':'fanyideskweb',
        'salt':'15439319935686',
        'sign':'3128d36874d6ee16567b76ebecefb2ac',
        'ts':'1543931993568',
        'bv':'0ef078d6b7f3e6f8047a6cbd85c069cc',
        'doctype':'json',
        'version':'2.1',
        'keyfrom':'fanyi.web',
        'action':'FY_BY_REALTIME',
        'typoResult':'false',
    }
    data = parse.urlencode(data)

    #设置headers头信息
    headers = {"Content-Length":len(data)}

    #创建请求，发送请求，爬取信息
    req = request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)

    #解析结果
    str_json = res.read().decode('utf-8')
    myjson = json.loads(str_json)
    print(myjson['translateResult'][0][0]['tgt'])

if __name__ == '__main__':
    while True:
        keyword = input('请输入你要翻译的文字：')
        if keyword == 'q':
            break
        fanyi(keyword)